package com.wanjia.bpsapi.crontab;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wanjia.bpsapi.pojo.entity.WjStoreProduct;
import com.wanjia.bpsapi.properties.TimedTaskProperties;
import com.wanjia.bpsapi.service.IVegeParamService;
import com.wanjia.bpsapi.service.IVegetableService;
import com.wanjia.bpsapi.service.IWjStoreProductService;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;


@Component
@Slf4j
public class TimedTaskVege {

    @Autowired
    TimedTaskProperties timedTaskProperties;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    IWjStoreProductService wjStoreProductService;

    @Autowired
    IVegetableService vegetableService;

    @Setter(onMethod_ = @Autowired)
    private IVegeParamService vegeParamService;


    public void run() {
        log.info("获取菜品信息定时任务执行中...");
        String vegeUrl = timedTaskProperties.getVegeUrl()+"?page=0&limit=9999999";
        HttpHeaders headers = new HttpHeaders();
        headers.add("Token", timedTaskProperties.getToken());
        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(vegeUrl, HttpMethod.GET, entity, String.class);
        String body = response.getBody();
        JSONObject jb = JSONObject.parseObject(body);
        JSONArray data = jb.getJSONObject("data").getJSONArray("data");
        wjStoreProductService.remove(new QueryWrapper<>());
        vegetableService.remove(new QueryWrapper<>());
        for (int i = 0; i < data.size(); i++) {
            JSONObject object = data.getJSONObject(i);
            WjStoreProduct wjStoreProduct = JSON.parseObject(String.valueOf(object), WjStoreProduct.class);
            wjStoreProductService.addProduct(wjStoreProduct);
            vegetableService.addVegetable(wjStoreProduct);
        }

        vegeParamService.fixData();
    }
}
